<?php
/**
 * Created by IntelliJ IDEA.
 * User: haoya_Coding_one
 * Date: 2019/3/23
 * Time: 14:23
 */

class View
{
    protected $variables = array();
    protected $_controller;
    protected $_action;

    function __construct($controller, $action){
        $this->_controller = $controller;
        $this->_action = $action;
    }

    /**
     * @param $name
     * @param $value
     * 分配变量
     */
    function assign($name, $value){
        $this->variables[$name] = $value;
    }

    /**
     * 渲染
     */
    function render(){
        $headers = getallheaders();
        var_dump($headers);
        $accept = $headers['Accept'];
        if (strpos($accept, 'application/json') !== false){
            $this->renderJson();
        }elseif (strpos($accept, 'text/html') !== false || strpos($accept, 'application/xhtml+xml') !== false){
            $this->renderHtml();
        }else{
            $this->renderString();
        }
    }
    function renderString(){
        header('Content-Type:application/text;charset=UTF-8');
        $resultArr=array();
        foreach ($this->variables as $key=>$value){
            $resultArr[]=$key.'='.$value;
        }
        exit(implode('&', $resultArr));
    }
    function renderJson(){
        header('Content-Type:application/json;charset=UTF-8');
        $result = array();
        $head = array();
        $head['time'] = date('Y-m-d H:i:s');
        $head['code'] = empty($this->variables['code'])?'0':$this->variables['code'];
        $head['msg'] = empty($this->variables['msg'])?'success':$this->variables['msg'];
        unset($this->variables['code']);
        unset($this->variables['msg']);
        $result['h'] = $head;
        $result['b'] = $this->variables;
        exit(json_encode($result, JSON_UNESCAPED_UNICODE));
    }
    /**
     * 渲染html页面
     */
    function renderHtml(){
        extract($this->variables);
        $defaultHeader = APP_PATH . 'application/views/header.php';
        $defaultFooter = APP_PATH . 'application/views/footer.php';
        $controllerHeader = APP_PATH . 'application/views/' . $this->_controller . '/header.php';
        $controllerFooter = APP_PATH .'application/views/' . $this->_controller . '/footer.php';
        if (file_exists($controllerHeader)){
            include ($controllerHeader);
        }else{
            include ($defaultHeader);
        }
        include (APP_PATH . 'application/views/' . $this->_controller . '/' . $this->_action . '.php');
        /*if (file_exists($controllerFooter)){
            include ($controllerFooter);
        }else{
            include ($defaultFooter);
        }*/
    }
}
